package com.movitech.mobile.cz.base.modules.suppliers.vo;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author Jack.Gong
 * @version 2018-02-11
 *
 */
public class BuildTree {
	
	// 构建树形结构
	public static <T> List<Tree<T>> build(List<Tree<T>> nodes) {
		List<Tree<T>> treeNodes = new ArrayList<>();
		List<Tree<T>> rootNodes = getRootNodes(nodes);
		for (Tree<T> rootNode : rootNodes) {
			buildChildNodes(rootNode, nodes);
			treeNodes.add(rootNode);
		}
		return treeNodes;
	}

	// 递归子节点
	public static <T> void buildChildNodes(Tree<T> node, List<Tree<T>> nodes) {
		List<Tree<T>> children = getChildNodes(node, nodes);
		if (!children.isEmpty()) {
			for (Tree<T> child : children) {
				buildChildNodes(child, nodes);
			}
			node.setChildren(children);
		}
	}

	// 获取父节点下所有的子节点
	public static <T> List<Tree<T>> getChildNodes(Tree<T> pnode, List<Tree<T>> nodes) {
		List<Tree<T>> childNodes = new ArrayList<>();
		for (Tree<T> n : nodes) {
			if (pnode.getId().equals(n.getParentId())) {
				childNodes.add(n);
			}
		}
		return childNodes;
	}

	// 判断是否为根节点
	public static <T> boolean rootNode(Tree<T> node, List<Tree<T>> nodes) {
		boolean isRootNode = true;
		for (Tree<T> n : nodes) {
			if (n.getId().equals(node.getParentId())) {
				isRootNode = false;
				break;
			}
		}
		return isRootNode;
	}

	// 获取集合中所有的根节点
	public static <T> List<Tree<T>> getRootNodes(List<Tree<T>> nodes) {
		List<Tree<T>> rootNodes = new ArrayList<>();
		for (Tree<T> n : nodes) {
			if (rootNode(n, nodes)) {
				rootNodes.add(n);
			}
		}
		return rootNodes;
	}

}
